<?php

namespace iBrand\Shop\Backend\Repository;

use iBrand\Component\Goods\Models\Goods;

class O2oGoodsRepository extends \iBrand\Shop\Core\Repositories\O2oGoodsRepository
{
	public function getGoodsPaginate($where, array $ids = [], $with = [], $limit = 20)
	{
		$query = $this->scopeQuery(function ($query) use ($where, $ids, $with) {
			if (is_array($where) AND count($where) > 0) {
				foreach ($where as $key => $value) {
					if ($key == 'goods') {
						continue;
					}

					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($ids)) {
				$query = $query->whereIn('goods_id', $ids);
			}

			if (!empty($with)) {
				foreach ($with as $item) {
					$query = $query->with($item);
				}
			}

			return $query->orderBy('id', 'desc');
		});

		if ($limit) {
			return $query->paginate($limit);
		} else {
			return $query->all();
		}
	}

	public function getGoodsIdsByCriteria($criteria)
	{
		$ids = Goods::where(function ($query) use ($criteria) {
			if (is_array($criteria) AND count($criteria) > 0) {
				foreach ($criteria as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			return $query;
		})->pluck('id')->toArray();

		if (count($ids) > 0) {
			return $ids;
		}

		return [];
	}
}
